package com.in.mobilerechargedth.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.in.mobilerechargedth.constant.ConstantVariables;
import com.in.mobilerechargedth.model.ChannelModel;


public class ChannelApi {
    public List<ChannelModel> getChannel() {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(ConstantVariables.API_CHANNEL_URL);
        List<ChannelModel> listChannelModel = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            StringBuilder builder = new StringBuilder();
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            String jsonString = builder.toString();
            if (!jsonString.equals("")) {
                JsonElement jElement = new JsonParser().parse(builder
                        .toString());
                JsonObject jObject = jElement.getAsJsonObject();
                if (jObject != null) {

                    String result = jObject.get("Result").getAsString();
                    Log.e("test", result);
                    if (result != null && result.equals("OK")) {
                        Log.e("test", result);
                        JsonArray JOperatorArray = jObject
                                .getAsJsonArray("data");
                        listChannelModel = new ArrayList<ChannelModel>();
                        for (int i = 0; i < JOperatorArray.size(); i++) {
                            ChannelModel channelModel = new ChannelModel();
                            JsonObject jMenuModel = JOperatorArray.get(i)
                                    .getAsJsonObject();

                            channelModel.setChannelName(jMenuModel.get(
                                    "CHANNELS_NAME").getAsString());

                            listChannelModel.add(channelModel);
                        }
                    } else {
                        return null;
                    }
                }
            } else {
                return null;
            }
            Log.e("test", jsonString);
        } catch (ClientProtocolException e) {

        } catch (IOException e) {
        }

        return listChannelModel;
    }
}